<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="userObj.query"
            clearable
            @clear="getUsers"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button
            type="primary"
            @click="addDialogVisible=true"
          >添加</el-button>
        </el-col>
      </el-row>

      <el-table
        :data="userlist"
        style="width: 100%"
        :stripe='true'
        border
      >
        <el-table-column
          label="#"
          type="index"
        >
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
        ></el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
        ></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- 因为上面绑定了:data="userlist",所以这里通过作用域插槽接受scope拿到数据 -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="getStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="174px"
        >
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="getEditUser(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 设置按钮 -->
            <el-tooltip
              effect="dark"
              content="分为角色"
              placement="top"
              :enterable='false'
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 页码部分 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userObj.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userObj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
        <!-- 页的个数的变化 -->
      </el-pagination>

      <!-- 用户添加对话框部分 -->
      <el-dialog
        title="添加用户信息"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <el-form
          :model="userForm"
          :rules="rulesForm"
          ref="ruleForm"
          label-width="100px"
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input v-model="userForm.username"></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
          >
            <el-input
              v-model="userForm.password"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="Email"
          >
            <el-input v-model="userForm.Email"></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="phonenumber"
          >
            <el-input v-model="userForm.phonenumber"></el-input>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="addUser"
          >确定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框部分 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          :model="editForm"
          :rules="editrules"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item label="用户名">
            <el-input
              v-model="editForm.username"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="mobile"
          >
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="editUser"
          >确定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    // 自定义邮箱的校验规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      return callback(new Error('请输入合法的邮箱'))
    }
    var checkPhoneNumber = (rule, value, callback) => {
      const regEmail = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regEmail.test(value)) {
        return callback()
      }
      return callback(new Error('请输入合法的手机号'))
    }
    return {
      userlist: [],
      // 请求传递的参数
      userObj: {
        query: '', // input输入框的值
        pagenum: 1, // 页码
        pagesize: 2 // 每一页的数据
      },
      total: 0, // 条数
      addDialogVisible: false, // 控制添加对话框的显示与隐藏
      editDialogVisible: false, // 控制修改对话框的显示与隐藏
      // 表单的数据对象,通过:model="userForm"绑定
      userForm: {
        username: '',
        password: '',
        Email: '',
        phonenumber: ''
      },
      // 表单的验证规则,通过 :rules="rulesForm"绑定
      rulesForm: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        Email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 通过validator调用自定义的规则checkEmail
          { validator: checkEmail, trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhoneNumber, trigger: 'blur' }
        ]
      },
      // 根据id查询到的用户数据(将要被修改的数据)
      editForm: {
      },
      // 修改的时候表单的验证规则
      editrules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 通过validator调用自定义的规则checkEmail
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhoneNumber, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    async getUsers() {
      const { data: res } = await this.$http.get('users', { params: this.userObj })
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 监听每一页数据的数量的改变的事件
    handleSizeChange(changeSize) {
      this.userObj.pagesize = changeSize
      this.getUsers()
    },
    // 监听当前页数量的变化
    handleCurrentChange(pagenum) {
      this.userObj.pagenum = pagenum
      this.getUsers()
    },
    // 监听switch开关状态的变化
    async getStateChanged(userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        // 如果请求失败就让页面的数据不切换
        userinfo.mg_state = !userinfo.mg_state
        this.$message.error('请求失败')
      }
      this.$message.success('更新角色成功！')
    },
    // 监听对话框的关闭事件  close,通过ref拿到表单的实例对象使用resetFields方法重置
    addDialogClose() {
      this.$refs.ruleForm.resetFields()
    },
    // 添加用户之前的验证
    // 注意自定义表单规则成功了也要return callback函数,不然valid不会执行
    addUser() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) {
          return
        }
        // 预验证(validate)通过了才能发起请求
        const { data: res } = await this.$http.post('users', {
          username: this.userForm.username,
          password: this.userForm.password,
          email: this.userForm.Email,
          mobile: this.userForm.phonenumber
        })
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUsers()
      })
    },
    // 查询要修改的用户信息,然后保存
    async getEditUser(id) {
      this.editDialogVisible = true
      // 保存根据id查询到的用户信息
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editForm = res.data
    },
    // 表单回到之前的那种重置操作
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
      console.log(111)
    },
    // 修改数据
    editUser() {
      // 提交之前的预验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          this.$message.error('更新用户状态失败')
        }
        // 更新成功,框框变隐藏
        this.editDialogVisible = false
        // 重新更新数据
        this.getUsers()
        // 提示更新成功
        this.$message.success('更新角色成功！')
      })
    },
    // 删除数据
    async deleteUser(id) {
      const isDelete = await this.$confirm('是否删除该用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，则返回值为字符串confirm
      // 如果用户取消了删除，则返回值为字符串cancel
      if (isDelete !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('成功删除用户')
      this.getUsers()
    }
  }
}
</script>
<style lang="scss" scoped>
</style>